<template>
  <div class="person">
    <h2>姓名：{{ person.name }}</h2>
    <h2>年龄：{{ person.age }}</h2>
    <h2>汽车：{{ person.car.c1 }}、{{ person.car.c2 }}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">修改年龄</button>
    <button @click="changeC1">修改第一辆车</button>
    <button @click="changeC2">修改第二辆车</button>
    <button @click="changeCar">修改整个车</button>
  </div>
</template>

<script setup lang="ts">
import { reactive, watch } from "vue";
let person = reactive({
  name: "张三",
  age: 8,
  car: {
    c1: "奔驰",
    c2: "宝马",
  },
});

function changeName() {
  person.name += "~";
}
function changeAge() {
  person.age += 1;
}
function changeC1() {
  person.car.c1 = "奥迪";
}
function changeC2() {
  person.car.c2 = "凯美瑞";
}
function changeCar() {
  person.car = { c1: "爱玛", c2: "雅迪" };
}
// 监视reactive对象中某个属性，且该属性是基本类型。写成getter函数式。否则无效监视元。
watch(() => person.name,(value, old) => {
    console.log(value, old);
  }
);

// 监视reactive对象中某个对象，写成getter函数式,这样可以监听整个对象改变。
// 注意：如果对象中某个属性改变时也需要监听，需要加上 {deep：true} 深度监听。
watch(() => person.car,(value, old) => {
    console.log(value, old);
  },{ deep: true }
);
</script>

<style>
.person {
  background-color: turquoise;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}

button {
  margin: 0 5px;
}
</style>
